<script>
import { isString } from '@/utils/kris_utils'
import dayjs from 'dayjs'

import FormWithDialog from '@/components/WorkExperienceForm/withDialog'
import Popconfirm from '@/components/PopconfirmNew/popconfirm'
import { FormStruct } from '@/components/WorkExperienceForm/index'
import Block from '../Block'

export default {
    components:{
        FormWithDialog,
        Popconfirm,
        Block
    },
    props:{
        isEditing:{
            type:Boolean,
            required:true,
            default:false
        },
        // 为了方便维护 自定定义一个结构 和外部的字段是不一致的
        // 以下两个函数的作用：
        // convertTo: 把内部的结构转换成外部结构
        // convertFrom: 把外部结构转换成内部结构
        convertTo:{
            type:Function,
            default:(value) => {
                return value
            }
        },
        convertFrom:{
            type:Function,
            default:(value) => {
                return value
            }
        },
        value:{
            type:Array,
            required:true,
            default(){
                return []
            }
        }
    },
    data(){
        return {
            editingIndex:null,
            formDialog:{
                draft:{ ...FormStruct },
                visible:false,
                mode:null, // EDIT || CREATE
            },
            tableData:[
                {
                    companyName:'Apple',
                    beginDate:new Date(),
                    endDate:new Date(),
                    department:'技术部',
                    post:'前端开发',
                    reasonForLeaving:'爱国',
                    companyPhone:'7777777',
                    salary:7777777,
                    scopeOfWork:'做APP，写前端'
                }
            ]
        }
    },
    computed:{
        workExperienceFormatted(){
            // 日期需要单独处理
            const exclude = ['beginDate','endDate']

            // 检查器
            const checker = (value) => {
                return value === undefined || 
                       value === null ||
                       (isString(value) && value.trim() === '')
            }


            return this
                .data
                // .map(item => this.convertFrom(item))
                .map(item => {
                    let result = this.withFallback(
                        exclude,
                        checker,
                        item,
                        '未填写'
                    )

                    // 日期单独做处理
                    result['beginDate'] = result['beginDate'] instanceof Date ? dayjs(result['beginDate']).format('YYYY-MM-DD'):'未填写'
                    result['endDate'] = result['endDate'] instanceof Date ? dayjs(result['endDate']).format('YYYY-MM-DD'):'未填写'

                    return result
                })
        },
        formDialogConfirmBtnText(){
            const { formDialog } = this,
                  m = { 'EDIT':'保存','CREATE':'添加' }

            if(formDialog.mode === null)
                return '确定'

            return m[formDialog.mode] ?? '确定'
        },
        data:{
            get(){
                return this.value
            },
            set(data){
                this.$emit('input',data)
            }
        }
    },
    watch:{
        'formDialog.draft':{
            handler(e){
                console.log(e)
            },
            deep:true
        }
    },
    methods:{
        withFallback(exclude,checker,obj,fallback){
            const reuslt = Object
                .entries(obj)
                .map(item => {
                    if(exclude.indexOf(item[0]) !== -1)
                        return item
                    
                    if(checker(item[1]))
                        item[1] = fallback

                    return item
                })

            return Object.fromEntries(reuslt)
        },
        
        handleFormConfirm(){
            if(this.formDialog.mode === 'EDIT')
                return this.saveRecord()

            if(this.formDialog.mode === 'CREATE')
                return this.createRecord()
        },


        showCreateDialog(){
            this.formDialog.mode = 'CREATE'
            this.formDialog.visible = true
            this.$refs['form'].resetFields?.()
        },
        handleEditing(index,row){
            this.formDialog = {
                draft:{...this.data[index]},
                mode:'EDIT',
                visible:true
            }
            this.editingIndex = index
        },

        saveRecord(){
            this.$set(this.data,this.editingIndex,{ ...this.formDialog.draft })
            this.editingIndex = null
            this.closeFormDialog()
        },
                createRecord(){
            if (!this.formDialog.draft.companyName) {
                this.$message.error('请输入公司名称')
            } else if (!this.formDialog.draft.companyPhone) {
                this.$message.error('请输入公司电话')
            }else if (!this.formDialog.draft.beginDate) {
                this.$message.error('请输入起始日期')
            }else if (!this.formDialog.draft.endDate) {
                this.$message.error('请输入结束日期')
            }else if (!this.formDialog.draft.department) {
                this.$message.error('请输入所在部门')
            }else if (!this.formDialog.draft.post) {
                this.$message.error('请输入工作岗位')
            }else if (!this.formDialog.draft.salary) {
                this.$message.error('请输入薪水')
            }else if (!this.formDialog.draft.reasonForLeaving) {
                this.$message.error('请输入离职原因')
            }else if (!this.formDialog.draft.scopeOfWork) {
                this.$message.error('请输入工作内容')
            }else{
                this.data.push({ ...this.formDialog.draft })
            this.closeFormDialog()
            }
        },
        deleteRecord(index){
            return async () => this.data.splice(index,1)
        },


        closeFormDialog(){
            this.formDialog.visible = false
            this.$nextTick(() => this.$refs['form'].resetFields?.())
        }
    }
}
</script>

<template>
    <div>
        <Block title="工作经历">
            <template #extra v-if="isEditing">
                <el-button 
                    @click="showCreateDialog" 
                    size="mini" 
                    type="primary"
                >
                    新增
                </el-button>
                
                <el-button :loading="$attrs.isSubmitting" @click="$emit('save')" size="mini">保存</el-button>
            </template>

            <FormWithDialog 
                ref="form"
                v-model="formDialog.draft"
                :visible.sync="formDialog.visible"
                :confirmText="formDialogConfirmBtnText"
                @cancel="closeFormDialog"
                @confirm="handleFormConfirm"
            />

            <el-table :data="workExperienceFormatted" border style="width: 100%">
                <el-table-column align="center" prop="companyName" label="公司名称" /> 
                <el-table-column align="center" prop="beginDate" label="起始日期" />
                <el-table-column align="center" prop="endDate" label="结束日期" /> 
                <el-table-column align="center" prop="department" label="所在部门" /> 
                <el-table-column align="center" prop="post" label="所在岗位" /> 
                <el-table-column align="center" prop="reasonForLeaving" label="离职原因" /> 
                <el-table-column align="center" prop="companyPhone" label="公司电话" /> 
                <el-table-column align="center" prop="salary" label="薪资" /> 
                <el-table-column align="center" prop="scopeOfWork" label="工作内容" /> 

                <el-table-column align="center" label="操作" v-if="isEditing">
                    <template slot-scope="scope">
                        <div class="row-actions">
                            <el-button 
                                size="mini" 
                                type="text"
                                @click="handleEditing(scope.$index,scope.row)"
                            >
                                编辑
                            </el-button>

                            <Popconfirm
                                :confirmFn="deleteRecord(scope.$index)"
                                title="确定删除吗？"
                            >
                                <el-button 
                                    size="mini" 
                                    type="text"
                                >
                                    删除
                                </el-button>
                            </Popconfirm>
                        </div>
                    </template>
                </el-table-column>

            </el-table>
        </Block>
    </div>
</template>

<style lang="scss">
    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: nowrap;
        padding: 20px 0;

        >.title {
            font-size: 16px;
            font-weight: 700;
            color: #303133;
        }

        >.actions {
            
        }
    }

    .row-actions {
        >* {
            margin-right: 4px;
        }
    }
</style>